package top.itbbn.otaifs;

import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;
import top.itbbn.utils.LogUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class OtaifsHelper {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();

    OtaifsReqStatus reqStatus;

    //单例模式

    //私有化构造方法使得该类无法在外部通过new 进行实例化
    private OtaifsHelper() {
    }

    //准备一个类属性，用于指向一个实例化对象，但是暂时指向null
    private static OtaifsHelper instance;

    //public static 方法，返回实例对象
    public static OtaifsHelper getInstance() {
        //第一次访问的时候，发现instance没有指向任何对象，这时实例化一个对象
        if (null == instance) {
            instance = new OtaifsHelper();
        }
        //返回 instance指向的对象
        return instance;
    }

    public void test1() throws InterruptedException {
        /*LogUtil.debug("begin");
        LogUtil.debug(OtaifsReq.getInstance().getRequestParam());
        LogUtil.debug("end");*/
        //OtaifsReqStatus status=new OtaifsReqStatus();
        //LogUtil.debug(JSONObject.toJSONString(status));
        long maxUseTime = 15000;
        reqStatus = new OtaifsReqStatus("总时长");
        int binfa = 20;//并发
        int allRequest = 100;//总请求数
        List<OtaifsReqStatus> listStatus = new ArrayList<OtaifsReqStatus>();
        for (int i = 0; i < allRequest; i++) {
            listStatus.add(new OtaifsReqStatus("任务"+i));
        }
        for (int i = 0; i < allRequest; i++) {
            int index = i;
            new Thread() {
                public void run() {
                    try {
                        listStatus.get(index).setPeroid("第"+(index/binfa+1)+"轮");
                        listStatus.get(index).setStart();
                        createPaymentReq(listStatus.get(index));

                    } catch (Exception e) {

                    }
                }
            }.start();
            if(i%binfa==0){
                System.out.println("达到并发数，休眼1秒");
                Thread.sleep(1000);
            }
        }
        boolean whileContinue = true;
        while (whileContinue) {
            whileContinue=false;
            for (int i = 0; i < allRequest; i++) {
                //System.out.println("current use:" + listStatus.get(i).isFihish);
                if (!listStatus.get(i).isFihish) {
                    whileContinue=true;
                    break;
                    //如果有1个未完成，就未完成
                }
            }
            long currentUse = reqStatus.getCurrentTimeUsed();
            //System.out.println("current use:" + currentUse);
            if (currentUse > maxUseTime) {

                //如果总体超时了
                whileContinue = false;
            }
            Thread.sleep(1000);

        }
        System.out.println("whileContinue:" + whileContinue);
        reqStatus.setEnd();
        LogUtil.debug(JSONObject.toJSONString(reqStatus));
    }

    public void createPaymentReq0(OtaifsReqStatus status) throws InterruptedException {
        long sleepTime = Math.round((Math.random() + 0) * 5000);
        Thread.sleep(sleepTime);
        status.setEnd();
        LogUtil.debug(JSONObject.toJSONString(status));
    }

    public void createPaymentReq(OtaifsReqStatus status) throws Exception {
        String url = "http://ota.zhiyoke.com/api.php/Api";
//        url = "http://local.lzj/otaifs/api.php/Api";
        RequestBody body = new FormBody.Builder()
                .add("method", OtaifsReq.getInstance().getMethod())
                .add("requestParam", OtaifsReq.getInstance().getRequestParam())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();


        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            Headers responseHeaders = response.headers();
           /* for (int i = 0; i < responseHeaders.size(); i++) {
                System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
            }
            System.out.println(response.body().string());*/
            //LogUtil.debug(response.body().string());
            status.setEnd();
            LogUtil.debug(JSONObject.toJSONString(status));
        }
    }
}
